package com.zhl.study.demo;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @description 这个是使用atomic和CAS实现的一个无锁的单向链表结构
 * @Author: z156940l@outlook.com
 * @className LockFreeLinkedList
 * @Date: 2024/4/10 16:49
 */
public class LockFreeLinkedList<T> {

    private final AtomicReference<Node<T>> head = new AtomicReference<>(null);

    private static class Node<T>{
        final T item;
        final AtomicReference<Node<T>> next;

        Node(T item, Node<T> next){
            this.item = item;
            this.next = new AtomicReference<>(next);
        }
    }

    public void add(T item){
        Node<T> newHead = new Node<>(item, null);
        Node<T> oldHead;

        do {
            oldHead = head.get();
            newHead.next.set(oldHead);
        } while (!head.compareAndSet(oldHead, newHead));
    }

    public void printList(){
        Node<T> current = head.get();
        while (current != null){
            System.out.print(current.item + " -> ");
            current = current.next.get();
        }
        System.out.print("null");
    }
}
